﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Core;
using MvcEngine.Core.Repositories;
using MvcEngine.Core.Validation;

using MvcEngine.Mvc.Filters;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Services;
using xVal.ServerSide;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Content;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Mvc.Models;
using MvcEngine.Core.Website;
using MvcEngine.Core.Account;

namespace MvcEngine.Mvc.BackOffice.Controllers
{
    public class PageController : BaseController
    {
        private IRoleRepository roleRepository = null;

        public PageController()
        {
            roleRepository = IoC.Resolve<IRoleRepository>();
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel List()
        {
            return new MvcEngineModelList<Page>()
            {
                List = ContentManager.Current.GetPages(false)
            };
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel New()
        {
            PageEditViewModel model = new PageEditViewModel()
            {
                Skins = SiteManager.Current.GetSkins(),
                PagePermissions = new List<PagePermission>(),
                Roles = AccountManager.Current.GetRoles(),
                Permissions = AccountManager.Current.GetPermissions()
            };

            Guid? skinId = SiteContext.Current.Skin.Id;
            if (skinId.HasValue)
            {
                model.SkinTemplates = SiteManager.Current.GetSkinTemlates(skinId.Value);
            }

            return model;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("New")]
        [ValidateInput(false)]
        [AntiForgeryValidationFilter]
        public object Create(Page page, PermissionViewModel[] permissions)
        {
            if (ModelState.IsValid)
            {
                page.Id = Guid.NewGuid();
                ContentManager.Current.SavePage(page);
                return Json(new { model = "valid" });
            }
            return Json(new { model = "invalid", errors = ModelState.GetErrors() });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(Guid pageId)
        {
            ContentManager.Current.DeletePage(pageId);
            return Redirect(Url.Pages());
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel Edit(Guid pageId)
        {
            Page page = ContentManager.Current.GetPage(pageId);

            PageEditViewModel model = new PageEditViewModel()
            {
                Id = page.Id,
                Description = page.Description,
                Header = page.Header,
                Keywords = page.Keywords,
                MenuTitle = page.MenuTitle,
                Name = page.Name,
                OrderNumber = page.OrderNumber,
                Visible = page.Visible,
                VisibleInMenu = page.VisibleInMenu,
                SkinId = page.SkinId,
                Skins = SiteManager.Current.GetSkins(),
                SkinTemplateId = page.SkinTemplateId,
                Title = page.Title,
                PagePermissions = AccountManager.Current.GetPagePermissions(pageId),
                Permissions = AccountManager.Current.GetPermissions(),
                Roles = AccountManager.Current.GetRoles()
            };

            Guid? skinId = page.SkinId;
            if (!skinId.HasValue)
            {
                skinId = SiteContext.Current.Skin.Id;
            }
            if (skinId.HasValue)
            {
                model.SkinTemplates = SiteManager.Current.GetSkinTemlates(skinId.Value);
            }

            return model;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("Edit")]
        [ValidateInput(false)]
        [AntiForgeryValidationFilter]
        public object EditSave(Page page, Guid pageId, PermissionViewModel[] permissions)
        {
            if (ModelState.IsValid)
            {
                page.Id = pageId;

                using (IUnitOfWork unitOfWork = UnitOfWorkHelper.Get())
                {
                    ContentManager.Current.SavePage(page);
                    var pagePermissions = AccountManager.Current.GetPagePermissions(pageId);
                    foreach (var permission in permissions)
                    {
                        var item = pagePermissions.SingleOrDefault(c => c.PermissionId == permission.Id && c.RoleId == permission.RoleId);
                        if (item != null)
                        {
                            if (!permission.Selected)
                            {
                                AccountManager.Current.DeletePagePermission(pageId, permission.Id, permission.RoleId);
                            }
                        }
                        else
                        {
                            if (permission.Selected)
                            {
                                var newPermission = IoC.Resolve<PagePermission>();
                                newPermission.Id = Guid.NewGuid();
                                newPermission.PageId = pageId;
                                newPermission.PermissionId = permission.Id;
                                newPermission.RoleId = permission.RoleId;
                                newPermission.CreatedBy = UserContext.Current.User.Id;
                                newPermission.CreatedDate = DateTime.Now;
                                newPermission.ModifiedBy = UserContext.Current.User.Id;
                                newPermission.ModifiedDate = DateTime.Now;
                                AccountManager.Current.AddPagePermission(newPermission);
                            }
                        }
                    }
                    unitOfWork.Commit();
                }
                return Json(new { model = "valid" });
            }
            return Json(new { model = "invalid", errors = ModelState.GetErrors() });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public object MoveUp(Guid pageId)
        {
            return null;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public object MoveDown(Guid pageId)
        {
            return null;
        }
    }
}
